<template>
    <view class="content flex flex-column" :class="['content-page-' + game.theme]" @tap="palyClickAudio"
	:style="[
        game.bg?'--content-bg:url('+game.bg+');':'',
        WEBCONFIG?.mine_sweeper_icon?'--item-icon:url('+WEBCONFIG?.mine_sweeper_icon+');':'',
        WEBCONFIG?.mine_sweeper_boom_icon?'--boom-icon:url('+WEBCONFIG?.mine_sweeper_boom_icon+');':'']">
        <view class="flex-1 flex flex-x-space-between flex-y-center px-10">
            <view class="pl-4">
				<view class="bg-danger text-white rounded-4 px-6 py-2 font-weight-600 text-center h8"
					hover-class="bg-danger-dark-1" @tap="close(true)">结束游戏</view>
            </view>
            <view class="text-center px-4 role-item" v-for="(role,index) in roles" :key="index"
            :class="{'role-select':index===CurrentRoleIndex}">
                <image :src="role.icon" class="role-icon"/>
                <view>X {{role.boom}}</view>
            </view>
        </view>
        <scroll-view class="block-body pb-safe-area" scroll-y>
            <view class="grid grid-gap-4 p-4">
                <view class="grid-column-4 block-item" v-for="(item,index) in list" :key="index"
                :class="{'bolck-selected':item===1,'block-boom':item.selected&&item.content}"
                @tap="selectedItme(index)"/>
            </view>
        </scroll-view>
        <toggle-sound />
		<x-popup v-model="showPopup" top="70vh" style="--x-popup-bg-image:var(--content-bg)" @hide="endGame">
			<view class="h6 font-weight-600 p-4 text-center rule-color">{{ taskItem.title }}</view>
			<view class="flex-1 flex flex-center px-4">
				<view class="h8 text-center font-weight-600 rule-color">{{ taskItem.content }}</view>
			</view>
		</x-popup>
    </view>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { onLoad, onUnload } from "@dcloudio/uni-app";
import { $http, $page, useGameCustom, createAudio } from '@/utils';
import { useWebConfigStore,useRefs } from '@/stores';
const webConfigStore = useWebConfigStore();
const { WEBCONFIG } = useRefs(webConfigStore);
const showPopup = ref(false);
const game = ref<any>({
    theme: '',
    bg:''
});
const search = ref({
    vip_id: 0,
    game: 'MINE_SWEEPER'
});
const roles = ref<any[]>([
	{
		boom: 0,
		nickname: '女生',
		icon: WEBCONFIG.value?.woman
	},
	{
		boom: 0,
		nickname: '男生',
		icon: WEBCONFIG.value?.man
	}
])
const list=ref<any[]>([]);
const clickAudioContext = createAudio('click');
const boomAudioContext = createAudio('boom');
onLoad((options: any) => {
    $page.title();
    if (options.id === 'custom') {
        const gameCustom = useGameCustom(search.value.game);
        gameCustom.get().then((data: any) => {
            initListData(data);
        }).catch((err: any) => {
            uni.showModal({
                title: '提示',
                content: err.msg,
                showCancel: false,
                confirmText: '返回',
                success: (res: any) => {
                    close();
                }
            })
        })
    } else {
        search.value.vip_id = options.id;
        getQuestionList();
    }
})
onUnload(() => {
    clickAudioContext.destroy();
})
let boomCount = 0;
const initListData=(data:any)=>{
    // list长度data.length的3-5倍且是6的倍数
    boomCount = data.length;
    let listLen = Math.ceil(Math.random() * 3 + 2) * 6;
	const info = uni.getSystemInfoSync();
    let topHeight = 100 + Math.max(info.safeArea?.top||0, 50);
    // #ifdef MP-WEIXIN
    topHeight = 100 + Math.max(info.safeArea?.top||0, 80);
    // #endif
	const offsetHeight=(info.safeArea?.height||info.windowHeight) - topHeight - 32 - info.windowBottom;
    const itemHeight = (info.safeArea?.width||info.windowWidth - 16) / 6;
    const minLen = Math.ceil(offsetHeight / itemHeight)*6;
    if(listLen<minLen){
        listLen=minLen;
    }
    const listData = new Array(listLen).fill(0);
    for (let i = 0; i < boomCount; i++) {
        listData[i] = data[i];
    }
    // 随机打乱排序
    shuffleArray(listData);
    list.value = listData;
}
const shuffleArray=(array:any[])=> {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
}
const getQuestionList = () => {
    $http.get('Question/list', {
        data: search.value
    })
        .then((res: any) => {
            if (res.code === $http.ResponseCode.SUCCESS) {
                game.value.theme=res.data.game.theme
                game.value.bg=res.data.game.bg
                if (res.data.game.rule_content) {
                    game.value.rule_content = res.data.game.rule_content;
                }
                initListData(res.data.list);
            } else {
                uni.showModal({
                    title: '提示',
                    content: res.msg,
                    showCancel: false,
                    confirmText: '返回',
                    success: (res: any) => {
                        close();
                    }
                })
            }
        }).catch((err: any) => {
        })
}
const taskItem = ref({
	title: '任务',
	content: '',
	icon: '',
	offRole:false
})
let CurrentRoleIndex = ref(0);
let selectedCount = 0;
let selectedBoomCount = 0;
const selectedItme=(index:number)=>{
    const item = list.value[index];
	let role = roles.value[CurrentRoleIndex.value];
    if(typeof item==='number'){
        if(item){
            return;
        }
        list.value[index]=1;
        CurrentRoleIndex.value++;
        if (CurrentRoleIndex.value >= roles.value.length) {
            CurrentRoleIndex.value = 0;
        }
    }else{
        taskItem.value.title = item.nature_text || '任务';
        // 当CurrentRoleIndex.value=0时，从role1是女生，role2是男生
        let role1 = roles.value[CurrentRoleIndex.value];
        let role2 = roles.value[CurrentRoleIndex.value === 0 ? 1 : 0];
        let content = item.content;
        // {$role1},{$role2}
        content = content.replaceAll('{$role1}', role1.nickname);
        content = content.replaceAll('{$role2}', role2.nickname);
        taskItem.value.content = content;
        taskItem.value.icon = item.icon;
        showPopup.value = true;
        taskItem.value.offRole=true;
        if(item.selected){
            return;
        }
        taskItem.value.offRole=false;
        boomAudioContext.restPlay();
        item.selected=true;
        role.boom++;
        selectedBoomCount++;
    }
    selectedCount++;
}
const endGame=()=>{
    if(taskItem.value.offRole||list.value.length<=0){
        return;
    }
	CurrentRoleIndex.value++;
	if (CurrentRoleIndex.value >= roles.value.length) {
		CurrentRoleIndex.value = 0;
	}
    if (selectedCount>=list.value.length||selectedBoomCount>=boomCount) {
        // 取出角色中炸弹最少的
        let minBoom = 0;
        let gameResult = '';
        for (let i = 0; i < roles.value.length; i++) {
            const item = roles.value[i];
            if (i === 0) {
                minBoom = item.boom;
                gameResult = item.nickname;
            } else {
                if (item.boom < minBoom) {
                    minBoom = item.boom;
                    gameResult = item.nickname;
                }
            }
        }
        uni.showModal({
            title: '游戏结束',
            content: `恭喜${gameResult}获胜`,
            confirmText: '重来',
            cancelText: '结束',
            success: (res: any) => {
                if (res.confirm) {
                    reset();
                } else {
                    close();
                }
            }
        })
    }
}
const reset = (confirm?: boolean) => {
	if (confirm) {
		uni.showModal({
			title: '提示',
			content: '确定要重来吗？',
			success: (res: any) => {
				if (res.confirm) {
					reset();
				}
			}
		})
		return;
	}
	roles.value.map((item: any) => {
		item.boom = 0;
	})
    for (let index = 0; index < list.value.length; index++) {
        const element = list.value[index];
        if (typeof element === 'number') {
            list.value[index] = 0;
        }else{
            element.selected = false;
        }
        
    }
    selectedCount = 0;
    selectedBoomCount = 0;
    CurrentRoleIndex.value = 0;
    showPopup.value = false;
    shuffleArray(list.value);
}
const close = (confirm?: boolean) => {
    if (confirm) {
        uni.showModal({
            title: '提示',
            content: '确定要结束游戏吗？',
            success: (res: any) => {
                if (res.confirm) {
                    close();
                }
            }
        })
        return;
    }
    $page.switch('/pages/index/index');
}
const palyClickAudio = () => {
    clickAudioContext.restPlay();
}
</script>

<style lang="scss" scoped>
.content {
    --content-bg: linear-gradient(180deg, #fdcbf1, #e6dee9);
    --item-bg-1: #df89b5;
    --item-bg-2: #bfd9fe;
    --rule-color: #df89b5;
    --item-icon: linear-gradient(180deg, var(--item-bg-1), var(--item-bg-2));
    width: 100vw;
    background-image: var(--content-bg);
    background-size: 100% 100%;
    background-repeat: no-repeat;
    overflow: hidden;
    backdrop-filter: blur(10px);
    position: relative;
	min-height: 100vh;
	padding-top: max(var(--window-top), 50px);
	// #ifdef MP-WEIXIN
	padding-top: max(var(--window-top), 80px);
	// #endif
	box-sizing: border-box;

    &-page-black {
        --content-bg: linear-gradient(180deg, #0c1014, #121c29);
        --item-bg-1: #27282d;
        --item-bg-2: #2e3035;
        --rule-color: var(--xl-white);
    }

    &-page-purple {
        --content-bg: linear-gradient(180deg, #4a4c92, #363455);
        --item-bg-1: #817fa4;
        --item-bg-2: #918fb3;
        --rule-color: var(--xl-white);
    }

    &-page-cyan {
        --content-bg: linear-gradient(180deg, #022227, #325b5d);
        --item-bg-1: #7a9ba0;
        --item-bg-2: #7d9ea3;
        --rule-color: var(--xl-white);
    }

    &-page-silvery {
        --content-bg: linear-gradient(180deg, #acb6bf, #506382);
        --item-bg-1: #c4cbd5;
        --item-bg-2: #a2a8b2;
        --rule-color: var(--xl-white);
    }
}
.rule-color{
	color: var(--rule-color);
}
.block-body{
    height: calc(100vh - 100px - max(var(--window-top), 50px));
	// #ifdef MP-WEIXIN
    height: calc(100vh - 100px - max(var(--window-top), 80px));
	// #endif
	box-sizing: border-box;
    .grid{
	    box-sizing: border-box;
    }
}
.block-item{
    height:calc((100vw - 0.75rem) / 6 - 0.75rem);
    background-color: var(--item-bg-1);
    border-radius: 0.375rem;
    background-image: var(--item-icon);
    background-size: 100% 100%;
    background-repeat: no-repeat;
}
.block-boom{
    background-image: var(--boom-icon);
}
.bolck-selected{
    background-image: none;
    background-color: transparent;
}
.role-icon{
    width: 40px;
    height: 40px;
}
.role-item{
    color: var(--rule-color);
}
.role-select{
    background-image: linear-gradient(180deg, var(--item-bg-1), var(--item-bg-2));
    border-radius: 0.375rem;
    background-size: 100% 100%;
    background-repeat: no-repeat;
    color: var(--rule-color);
}
</style>
